package com.yy.job.core.config.validator;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import com.google.common.collect.Lists;
import com.yy.job.common.enums.ErrorCodeEnum;
import com.yy.job.core.config.xml.JobStepXmlConfig;
import com.yy.job.core.config.xml.JobXmlConfig;
import com.yy.job.utils.DataValidator;
import com.yy.job.utils.exception.YYJobRuntimeException;

/**
 * 校验器
 * 
 * @author eleven.li
 *
 */
public class JobXmlConfigValidator {

	public static void validate(String moduleCode, JobXmlConfig jobXmlConfig) {
		if (jobXmlConfig == null) {
			throw new YYJobRuntimeException(ErrorCodeEnum.CHECK_JOB_ERROR, moduleCode, "no jobConfig");
		}

		String jobCode = jobXmlConfig.getJobCode();
		if (StringUtils.isBlank(jobCode)) {
			throw new YYJobRuntimeException(ErrorCodeEnum.CHECK_JOB_CONFIG, moduleCode, "", "jobCode is empty");
		}
		if (StringUtils.isBlank(jobXmlConfig.getJobName())) {
			throw new YYJobRuntimeException(ErrorCodeEnum.CHECK_JOB_CONFIG, moduleCode, jobCode, "jobName is empty");
		}

		if (StringUtils.isNotBlank(jobXmlConfig.getLockTime())
				&& !DataValidator.isPosInteger(jobXmlConfig.getLockTime())) {
			throw new YYJobRuntimeException(ErrorCodeEnum.CHECK_JOB_CONFIG, moduleCode, jobCode,
					"lockTime is not positive integer");
		}

		if (CollectionUtils.isNotEmpty(jobXmlConfig.getJobStepConfigs())) {
			List<String> jobStepCodeList = Lists.newArrayList();
			for (JobStepXmlConfig jobStepConfig : jobXmlConfig.getJobStepConfigs()) {
				// 校验jobTaskConfig节点的配置
				JobStepXmlConfigValidator.validate(moduleCode, jobCode, jobStepConfig);

				// 校验stepCode是否重复
				String stepCode = jobStepConfig.getStepCode();
				if (jobStepCodeList.contains(stepCode)) {
					throw new YYJobRuntimeException(ErrorCodeEnum.CHECK_STEP_CONFIG, moduleCode, jobCode, stepCode,
							"stepCode is duplicated");
				}
				jobStepCodeList.add(stepCode);
			}
		}
	}

}
